package peer;

import java.util.ArrayList;
import java.util.UUID;

import message.Message;
import message.MessageHandler;
import message.NeighborMessage;
import message.MessageActions;

public class Peer implements MessageActions {

	private ArrayList<Message> messageHistory = new ArrayList<Message>();
	public ArrayList<Neighbor> neighborList = new ArrayList<Neighbor>();
	MessageHandler messageHandler;
	volatile int port = -1;
	Thread messageHandlerThread;
	String parentIp;
	int parentPort;

	public Peer(Neighbor parent) {
		messageHandler = new MessageHandler(this);
		messageHandlerThread = new Thread(messageHandler);
		messageHandlerThread.start();
		parentIp = parent.getIp();
		parentPort = parent.getPort();

		new Thread() {
			public void run() {
				while (port == -1) {
					try {
						sleep(500);
					} catch (InterruptedException e) {
						// TODO: handle exception
					}
				}
				System.out
						.println("messageHandler is running on port: " + port);

				NeighborMessage neighborMessage = new NeighborMessage(
						new Message(Message.NEIGHBOR, parentIp, parentPort, UUID.randomUUID(),
								   "localhost"+ "," + port));
				messageHandler.sendMessage(neighborMessage);
				System.out.println("starting spawn/leave processes");
				spawn();
				leave();
			}

		}.start();

	}

	public ArrayList<Message> getMessageHistory() {
		return messageHistory;
	}

	public ArrayList<Neighbor> getNeighborList() {
		return neighborList;
	}

	public void addNeighbors(ArrayList<Neighbor> newNeighbors) {
		for (Neighbor neighbor : newNeighbors) {
			if (!neighborList.contains(neighbor)) {
				neighborList.add(neighbor);
			}
		}
	}

	public void setPort(int port) {
		this.port = port;
	}

	private void spawn() {
		new Thread() {
			public void run() {
				int maxspawn = 2;
				int i = 0;
				while (i < maxspawn) {
					try {
						sleep(100 * 30);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					int random = (int) (Math.random() * 100);
					if (random > 80) {
						PeerUI ui = new PeerUI();
						ui.setVisible(true);
						new Peer(new Neighbor("127.0.0.1", port));
						i++;
					}
				}
				System.out.println("spawn() terminated");
			}
		}.start();
	}

	private void leave() {
	}

	@Override
	public void unknownType(Message m) {
		// TODO Print debugging informations 
	}
}
